package a51qindian.com.comprehensive.activity;

import android.Manifest;
import android.app.Activity;
import android.app.TimePickerDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.text.InputType;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.TimePicker;

import com.bumptech.glide.Glide;
import com.li.utils.BitmapUtil;
import com.li.utils.ImageUtil;
import com.li.utils.KeyboardUtil;
import com.li.utils.ScreenUtil;
import com.li.utils.ToastUtil;
import com.li.utils.UriUtil;
import com.li.widget.DoubleTextView;
import com.li.widget.MultipleLayout;
import com.li.widget.TagImageView;
import com.li.widget.TextEditText;
import com.li.widget.TopNavigationBar;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import a51qindian.com.comprehensive.App;
import a51qindian.com.comprehensive.Const;
import a51qindian.com.comprehensive.R;
import a51qindian.com.comprehensive.base.QDBaseActivity;
import a51qindian.com.comprehensive.model.BaseModel;
import a51qindian.com.comprehensive.model.UserDetailInfo;
import a51qindian.com.comprehensive.net.ObservableHelper;
import a51qindian.com.comprehensive.net.RetrofitCreator;
import a51qindian.com.comprehensive.net.SelectorObserver;
import a51qindian.com.comprehensive.util.SpUtil;
import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

/**
 * Author: Li
 * Date: 2017/9/28 0028
 * Description: 完善商铺信息
 */

public class PerfectShopInfoActivity extends QDBaseActivity {


    @BindView(R.id.top_navigation)
    TopNavigationBar mTopNavigation;
    @BindView(R.id.layout_content)
    MultipleLayout mLayoutContent;

    @BindView(R.id.btn_confirm)
    Button mBtnConfirm;
    @BindView(R.id.txt_name)
    TextEditText mTxtName;
    @BindView(R.id.txt_phone)
    TextEditText mTxtPhone;

    @BindView(R.id.txt_address)
    TextView mTxtAddress;
    @BindView(R.id.et_address)
    EditText mEtAddress;

    @BindView(R.id.txt_store_name)
    TextEditText mTxtStoreName;
    @BindView(R.id.txt_avg_consumption)
    TextEditText mTxtAvgConsumption;
    @BindView(R.id.txt_short_name)
    TextEditText mTxtShortName;
    @BindView(R.id.txt_start_time)
    DoubleTextView mTxtStartTime;
    @BindView(R.id.txt_end_time)
    DoubleTextView mTxtEndTime;


    @BindView(R.id.layout_img)
    LinearLayout mLayoutImg;

    private Uri mUri;
    private TagImageView mCurrentImg;
    private LinearLayout.LayoutParams mParams;
    private File mFile;
    private String mAddressPre="";

    @Override
    protected int getLayoutId() {
        return R.layout.activity_perfect_shop_info;
    }

    private static final String IMG_NAME = "tmp.jpg";

    private TagImageView mAddView;

    @Override
    protected void initSth() {
        super.initSth();
        mTopNavigation.setNavigationBarListener(this);
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) ==
                PackageManager.PERMISSION_GRANTED &&
                ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA) ==
                        PackageManager.PERMISSION_GRANTED) {
            generateUri();
        } else {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA}, 1);
        }

        mTxtStartTime.setTxtRight("9:00");
        mTxtEndTime.setTxtRight("22:00");


        mAddView = new TagImageView(this);
        mAddView.setBackground(ContextCompat.getDrawable(this, R.drawable.shape_bg));
        int width = (int) (ScreenUtil.getScreenWidth(this) * 1.0f / 4);
        int height = (int) (ScreenUtil.getScreenHeight(this) * 1.0f / 4);
        width = width == 0 ? 108 * 2 : width;
        height = height == 0 ? 192 * 2 : height;
        mParams = new LinearLayout.LayoutParams(width, height);
        mParams.setMargins(10, 10, 10, 10);
        mAddView.setTagEx("add");
        mAddView.setImageResource(R.drawable.ic_add_img);
        mAddView.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
        mLayoutImg.addView(mAddView, mParams);
        mAddView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mCurrentImg = (TagImageView) v;
                showChooseDialog(v);
            }
        });
        setAddressPre(mUid,"android");
        mTxtPhone.getEditText().setInputType(InputType.TYPE_CLASS_PHONE);
        mTxtAvgConsumption.getEditText().setInputType(InputType.TYPE_NUMBER_FLAG_DECIMAL|InputType.TYPE_CLASS_NUMBER);
    }

    private void setAddressPre(String uid,String request){
        Map<String, String> map = new HashMap<>();
        map.put("uid", uid);
        map.put("request", request);
        ObservableHelper.createObservable(RetrofitCreator.createService().userDetailInfo(map))
                .subscribe(new SelectorObserver<BaseModel<UserDetailInfo>>() {
                    @Override
                    protected void onErrorCodeInfo(int code, String info) {

                    }

                    @Override
                    protected void onSuccess(BaseModel<UserDetailInfo> userDetailInfoBaseModel) {
                        UserDetailInfo detailInfo = userDetailInfoBaseModel.getData();
                        mAddressPre=detailInfo.getShop_address();
                        mTxtAddress.setText("店铺地址："+detailInfo.getShop_address());
                    }

                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        addDisposable(d);
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                    }
                });
    }
    private void resetOnClick() {
        for (int i = 0; i < mLayoutImg.getChildCount(); i++) {
            TagImageView imageView = (TagImageView) mLayoutImg.getChildAt(i);
            String tag = imageView.getTagEx();
            if (!tag.equals("add")) {
                imageView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mCurrentImg = (TagImageView) v;
                        showChooseDialog(v);
                    }
                });

            }
        }
    }

    private void shouldShow() {
        int count = mLayoutImg.getChildCount();
        if (count == 6) {
            mAddView.setVisibility(View.GONE);
        } else {
            mAddView.setVisibility(View.VISIBLE);
        }
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @android.support.annotation.NonNull String[] permissions, @android.support.annotation.NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 1) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED
                    && grantResults[1] == PackageManager.PERMISSION_GRANTED) {
                generateUri();
            } else {
                ToastUtil.showToast(PerfectShopInfoActivity.this, "未授予权限可能导致应用出现问题");
            }
        }
    }

    private static final int CODE_GALLERY_REQUEST = 0xa0;
    private static final int CODE_CAMERA_REQUEST = 0xa1;
    private static final int CODE_RESULT_REQUEST = 0xa2;

    private void generateUri() {
        File fileDir = new File(getExternalCacheDir(), "xiaosui");
        if (!fileDir.exists()) {
            fileDir.mkdirs();
        }
        mFile = new File(fileDir, IMG_NAME);
        if (!mFile.exists()) {
            try {
                mFile.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (Build.VERSION.SDK_INT >= 24) {
            mUri = ImageUtil.getImageContentUri(this, mFile);
        } else {
            mUri = Uri.fromFile(mFile);
        }
    }

    @OnClick({R.id.btn_confirm, R.id.txt_start_time, R.id.txt_end_time})
    public void onViewClicked(View view) {
        switch (view.getId()) {

            case R.id.btn_confirm:

                if (mLayoutImg.getChildCount()<6) {

                    showToast("图片未选择完全(共五张)");
                    return;
                }

                TagImageView tagImg1= (TagImageView) mLayoutImg.getChildAt(0);
                TagImageView tagImg2= (TagImageView) mLayoutImg.getChildAt(1);
                uploadShopInfo(SpUtil.getUserInfo(PerfectShopInfoActivity.this, SpUtil.USER_ID),
                        mTxtName.getEtTxt(), mTxtPhone.getEtTxt(), mAddressPre+mEtAddress.getText().toString(),
                        mTxtStoreName.getEtTxt(), mTxtAvgConsumption.getEtTxt(), mTxtStartTime.getTxtRight(),
                        mTxtEndTime.getTxtRight(), tagImg1.getTagEx(),
                        mTxtShortName.getEtTxt(), tagImg2.getTagEx(), getShopImg()
                );
                break;
            case R.id.txt_start_time:
                TimePickerDialog dialog = new TimePickerDialog(PerfectShopInfoActivity.this,
                        new TimePickerDialog.OnTimeSetListener() {
                            @Override
                            public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                                mTxtStartTime.setTxtRight(hourOfDay + ":" + (minute < 10 ? ("0" + minute) : minute));
                            }
                        }, 7, 0, true);
                dialog.show();
                break;
            case R.id.txt_end_time:
                TimePickerDialog endTimeDialog = new TimePickerDialog(PerfectShopInfoActivity.this,
                        new TimePickerDialog.OnTimeSetListener() {
                            @Override
                            public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                                mTxtEndTime.setTxtRight(hourOfDay + ":" + (minute < 10 ? ("0" + minute) : minute));
                            }
                        }, 19, 0, true);
                endTimeDialog.show();
                break;

        }
    }

    private void showChooseDialog(View view) {
        KeyboardUtil.hideKeyboard(PerfectShopInfoActivity.this, view);
        AlertDialog.Builder builder = new AlertDialog.Builder(PerfectShopInfoActivity.this)
                .setTitle("选择来源")
                .setItems(new String[]{"相机", "图库"}, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        switch (which) {
                            case 0:
                                ImageUtil.takePicture(PerfectShopInfoActivity.this, CODE_CAMERA_REQUEST, mUri);
                                break;
                            case 1:
                                ImageUtil.chooseLocaleImage(PerfectShopInfoActivity.this, CODE_GALLERY_REQUEST);
                                break;
                        }
                    }
                });
        builder.create().show();
    }



    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case CODE_GALLERY_REQUEST:
                if (resultCode == Activity.RESULT_OK) {

                    uploadFile(new File(BitmapUtil.compressImageUpload(
                            UriUtil.getRealPathFromUri(mContext,data.getData()))));
//                    realUri = Uri.fromFile(new File(getExternalCacheDir(), "head.jpg"));
//                    ImageUtil.crop(PerfectShopInfoActivity.this, data.getData(),
//                            realUri, CODE_RESULT_REQUEST, mCurrentImg.getWidth() * 2,
//                            mCurrentImg.getHeight() * 2);
                }

                break;
            case CODE_CAMERA_REQUEST:
                if (resultCode == Activity.RESULT_OK) {
                    uploadFile(new File(BitmapUtil.compressImageUpload(mFile.getAbsolutePath())));
//                    realUri = Uri.fromFile(new File(getExternalCacheDir(), "head.jpg"));
//                    ImageUtil.crop(this, null, realUri, CODE_RESULT_REQUEST,
//                            mCurrentImg.getWidth() * 2, mCurrentImg.getHeight() * 2);
                }

                break;
            case CODE_RESULT_REQUEST:
                if (resultCode == Activity.RESULT_OK) {
                    uploadFile(new File(getExternalCacheDir(), "head.jpg"));
                }
                break;
        }

    }

    /**
     * 上传图片
     *
     * @param file 图片文件
     */
    private void uploadFile(File file) {
        mLayoutContent.onLoadingWithContent("正在上传");
        mBtnConfirm.setEnabled(false);
        RequestBody requestFile =
                RequestBody.create(MediaType.parse("multipart/form-data"), file);
        MultipartBody.Part body =
                MultipartBody.Part.createFormData("photo", file.getName(), requestFile);
        ObservableHelper.createObservable(RetrofitCreator.createService().uploadFile(body))
                .subscribe(new Observer<String>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        addDisposable(d);
                    }

                    @Override
                    public void onNext(String s) {
                        mLayoutContent.onSuccess();
                        mBtnConfirm.setEnabled(true);
                        try {
                            JSONObject object = new JSONObject(s);
                            ToastUtil.showToast(PerfectShopInfoActivity.this, object.getString("info"));
                            object = object.getJSONObject("data");
                            String path = object.getString("path");
                            Log.e("tag", "onNext: " + path);

                            if (mCurrentImg.getTagEx().equals("add")) {
                                TagImageView imageView = new TagImageView(PerfectShopInfoActivity.this);
                                imageView.setTagEx(String.valueOf(object.getString("photo_id")));
                                imageView.setScaleType(ImageView.ScaleType.FIT_XY);
                                Glide.with(PerfectShopInfoActivity.this).load(path).into(imageView);
                                mLayoutImg.addView(imageView, mLayoutImg.getChildCount() - 1, mParams);
                                shouldShow();
                                resetOnClick();
                            } else {
                                mCurrentImg.setTagEx(String.valueOf(object.getString("photo_id")));
                                Glide.with(PerfectShopInfoActivity.this).load(path).into(mCurrentImg);
                            }


                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        mLayoutContent.onSuccess();
                        ToastUtil.showToast(PerfectShopInfoActivity.this, e.getMessage());
                        mBtnConfirm.setEnabled(true);
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    /**
     * 上传商铺信息
     *
     * @param uid       用户编号
     * @param shopName  商铺名
     * @param phone     电话
     * @param address   商铺地址
     * @param ownerName 店长名
     * @param avg       平均消费
     * @param startTime 开始营业时间
     * @param endTime   停止营业时间
     * @param photoId   图片ID
     */
    private void uploadShopInfo(String uid, String shopName, String phone, String address, String ownerName, String avg,
                                String startTime, String endTime, String photoId, String shortName,
                                String license, String shopImg) {


        mLayoutContent.onLoadingWithContent();
        Map<String, String> map = new HashMap<>();
        map.put("uid", uid);
        map.put("name", shopName);
        map.put("mobile", phone);
        map.put("address", address);
        map.put("shopowner", ownerName);
        map.put("ave_price", avg);
        map.put("bgtime", startTime);
        map.put("edtime", endTime);
        map.put("titlepic", photoId);
        map.put("short_name", shortName);
        map.put("license", license);
        map.put("shop_img", shopImg);
        ObservableHelper.createObservable(RetrofitCreator.createService().perfectShop(map))
                .subscribe(new Observer<String>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        addDisposable(d);
                    }

                    @Override
                    public void onNext(@NonNull String s) {
                        mLayoutContent.onSuccess();
                        try {
                            JSONObject object = new JSONObject(s);
                            if (object.getInt("code") != 1) {
                                ToastUtil.showToast(PerfectShopInfoActivity.this, object.getString("info"));
                                return;
                            }
                            SpUtil.updateUserInfo(PerfectShopInfoActivity.this, SpUtil.USER_IS_SHOP, "1");
                            Intent intent = new Intent(PerfectShopInfoActivity.this, MainActivity.class);
                            intent.putExtra(Const.USER_TYPE,
                                    SpUtil.getUserInfo(PerfectShopInfoActivity.this, SpUtil.USER_GRADE));
                            startActivity(intent);
                            finish();
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        mLayoutContent.onSuccess();
                        ToastUtil.showToast(PerfectShopInfoActivity.this, e.getMessage());
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    @Override
    public void onFunctionTxtListener(View view) {
        super.onFunctionTxtListener(view);
        Intent intent = new Intent(PerfectShopInfoActivity.this, LoginActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        App.clearActivity();
        SpUtil.clearUserInfo(PerfectShopInfoActivity.this);
        startActivity(intent);
        finish();
    }

    private String getShopImg() {

        String tag1 = ((TagImageView)mLayoutImg.getChildAt(2)).getTagEx();
        String tag2 = ((TagImageView)mLayoutImg.getChildAt(3)).getTagEx();
        String tag3 = ((TagImageView)mLayoutImg.getChildAt(4)).getTagEx();
        return tag1 + "|" + tag2 + "|" + tag3;
    }
}
